package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.entity.Dish;
import com.itheima.entity.DishDto;
import com.itheima.entity.DishFlavor;
import com.itheima.mapper.DishMapper;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishflavor;

    @Override
    public void saveWithFlovars(DishDto dishDto) {
        this.save(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();
        Long id = dishDto.getId();
        flavors = flavors.stream().map(item -> {
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());
        boolean b = dishflavor.saveBatch(flavors);
    }

    @Override
    public Dish getByIdWithFlavor(Long id) {
        Dish DishById = this.getById(id);
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, DishById.getId());
        List<DishFlavor> FlavorList = dishflavor.list(lqw);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(DishById, dishDto);
        dishDto.setFlavors(FlavorList);
        return dishDto;

    }

    @Override
    public void UpdateWithFlovars(DishDto dishDto) {
        this.updateById(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(flavors != null, DishFlavor::getDishId, dishDto.getId());
        dishflavor.remove(lqw);
        dishflavor.saveBatch(flavors);
    }
}
